package com.hmdp.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.bean.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     */
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            //2.不符合，返回错误信息
            return Result.fail("手机号格式错误");
        }
        //2.符合，生成验证码
        String code = RandomUtil.randomNumbers(6);
        //3.保存验证码到session
        //session.setAttribute("code", code);
        //3.保存验证码到Redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        //4.发送验证码
        log.debug("验证码发送成功，验证码:{}",code);
        return Result.ok();
    }
    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号、验证码
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)){
            //不符合，返回错误信息
            return Result.fail("手机号格式错误");
        }
        String code = loginForm.getCode();
        //从Redis中拿到验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        //String cacheCode = (String) session.getAttribute("code");
        if(code == null || !code.equals(cacheCode)){
            return Result.fail("验证码错误");
        }
        //2.根据手机号，查找用户数据表，是否存在该用户
        //MyBatisPlus的查询功能
        User user = query().eq("phone", phone).one();
        //3.不存在，新增用户，
        if(user==null) {
            user = createUserWithPhone(phone);
        }
        //4.将用户数据user保存到session中,保存信息过多，只保存userDto里的信息
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user,userDTO);
        //session.setAttribute("user",userDTO);
        //session.setAttribute("user",BeanUtils.copyProperties(user,userDTO.calss));
        //4.将用户信息保存到Redis中
        //4.1随机生成token作为登陆令牌
        String token = UUID.randomUUID().toString(true);
        //4.2将userDTO转成hash，但userDTO里面id存储的是long类型，通过BeanUtil.beanToMap不能转为String
        //法一，不用BeanUtil.beanToMap
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", user.getId().toString());
        userMap.put("nickName", user.getNickName());
        userMap.put("icon", user.getIcon());
        //法二
        //Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
        //       CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue) -> fieldName.toString()));
        //4.3将用户信息保存到Redis中
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMap);
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL,TimeUnit.MINUTES);
        //5.返回登录结果
        return Result.ok(token);
    }
    /**
     * 实现签到功能
     * @return
     */
    @Override
    public Result sign() {
        //1.获取当前用户id
        Long id = UserHolder.getUser().getId();
        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //3.拼接key
        String format = now.format(DateTimeFormatter.ofPattern(":yyyy-MM"));
        String key=USER_SIGN_KEY+id+format;
        //4.获取本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.写入Redis中
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }
    /**
     * 连续签到天数统计
     * @return
     */
    @Override
    public Result signCount() {
        //1.获取当前用户id
        Long id = UserHolder.getUser().getId();
        //2.获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //3.拼接key
        String format = now.format(DateTimeFormatter.ofPattern(":yyyy-MM"));
        String key=USER_SIGN_KEY+id+format;
        //4.获取本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //5.查询redis中本月截至到今天所有的签到记录,拿到的是一个十进制的数
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key,
                BitFieldSubCommands.create().
                        get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).
                        valueAt(0));
        if(result==null|| result.isEmpty()){
            return Result.ok();
        }
        //6.循环遍历依次取出签到记录，做判断
        int count=0;
        long l = result.get(0);
        while (true) {
            //6.1让二进制数与1做与运算，得到最后一天签到记录bit位
            long l1 = l & 1;
            //6.2判断该bit位是0还是1
            if(l1==0){
                //6.3是0，不存在连续签到情况，结束
                break;
            }else{
                //6.4不是0，连续签到天数count+1
                count++;
            }
            l >>>= 1;
        }
        return Result.ok(count);
    }

    /**
     * 支付
     * @return
     * @param orderId
     */
    @Override
    public Result pay(Long orderId) {

        return null;
    }

    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX +RandomUtil.randomString(10));
        //MyBatisPlus的保存功能
        save(user);
        return user;
    }
}
